package com.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.DTO.LoginFormDTO;
import com.example.DTO.UserDTO;
import com.example.common.Result;
import com.example.domain.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import com.example.utils.RegexUtils;
import com.example.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.example.common.RedisContants.*;

/**
 * @author chenliang
 * @description 针对表【tb_user】的数据库操作Service实现
 * @createDate 2023-11-09 18:10:19
 */
@Service
@Slf4j
@SessionAttributes("user")
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    public UserMapper userMapper;
    @Resource
    public StringRedisTemplate stringRedisTemplate;

    /**
     * 发送验证码
     *
     * @param phone
     * @param request
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpServletRequest request) {
        //1、校验手机号
        if (!RegexUtils.isPhoneInvalid(phone)) {
            //2、如果不符合，返回错误信息
            return Result.fail("手机号格式错误！！！");
        }
        //2、生成随机验证吗
        String code = RandomUtil.randomNumbers(6);
        //保存验证码到session中
        request.getSession().setAttribute("code", code);
        request.getSession().setAttribute("phone", phone);
        //4、保存验证码到redis
        //设置key有效期2分钟
        stringRedisTemplate.opsForValue()
                .set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //4、打印日志
        log.debug("发送短信验证码成功，验证码:{}", code);
        return Result.ok("发送短信验证码成功，验证码:" + code);
    }

    /**
     * 基于session实现用户登录
     *
     * @param loginFormDTO
     * @param request
     * @return
     */
    @Override
    public Result SessionLogin(LoginFormDTO loginFormDTO, HttpServletRequest request) {
        //1、首先校验手机号和验证码是否合法
        String phone = loginFormDTO.getPhone();
        if (!RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！！！");
        }
        //2、校验验证码
        Object cachecode = request.getSession().getAttribute("code");
        String dtoCode = loginFormDTO.getCode();
        if (dtoCode == null || !dtoCode.equals(cachecode.toString())) {
            return Result.fail("验证码错误！！");
        }
        //2、校验手机号是否和获取验证码的手机号一致
        Object cachephone = request.getSession().getAttribute("phone");
        String dtoPhone = loginFormDTO.getPhone();
        if (cachephone == null || !dtoPhone.equals(cachephone.toString())) {
            return Result.fail("手机号错误！！");
        }
        //3、根据手机号查询用户信息
        User user = query().eq("phone", phone).one();
        if (user == null) {
            //创建用户
            user = CreateUser(phone);
        }
        //5、保存用户信息到session中
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        request.getSession().setAttribute("user", userDTO);
        //使用完验证码后立即移除
        request.getSession().removeAttribute("code");
        request.getSession().removeAttribute("phone");
        return Result.ok(userDTO);
    }

    /**
     * 基于Redis用户登录
     *
     * @param loginFormDTO
     * @param session
     * @return
     */
    @Override
    public Result RedisLogin(LoginFormDTO loginFormDTO, HttpSession session) {
        //1、首先校验手机号和验证码是否合法
        String phone = loginFormDTO.getPhone();
        if (!RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！！！");
        }
        //2、校验验证码
        String key = LOGIN_CODE_KEY + phone;
        String cachecode = stringRedisTemplate.opsForValue().get(key);
        String code = loginFormDTO.getCode();
        if (cachecode == null || !cachecode.equals(code)) {
            //3、不一致：报错
            return Result.fail("验证码错误！！");
        }
        //3、根据手机号查询用户信息
        User user = query().eq("phone", phone).one();
        if (user == null) {
            //创建用户
            log.debug("用户不存在，自动创建！");
            user = CreateUser(phone);
        }
        //保存用户信息到redis中
        /**
         * 1)随机生成token作为登陆令牌
         * 2)将user对象转为hash存储
         * 3)存储
         */
        //7.1、随机生成token作为登陆令牌
        String token = UUID.randomUUID().toString(true);
        String tokenkey = LOGIN_USER_KEY + token;
        //将user对象转成hashmap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //将存储的user对象中的所有类型改成string类型
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(tokenkey, userMap);
        //保存用户信息到Localhost中
        UserHolder.saveUser(userDTO);
        //设置token有效期——半个小时
        stringRedisTemplate.expire(tokenkey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.ok("用户token信息为：" + token);
    }

    /**
     * 用户签到
     *
     * @return
     */
    @Override
    public Result sign() {
        //1、获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //2、获取日期
        LocalDateTime now = LocalDateTime.now();
        //3、拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //4、获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //5、写入Redis,  SETBIT key offset 1
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        log.debug("用户签到成功!!!");
        return Result.ok("用户签到成功");
    }

    /**
     * 用户连续签到次数
     *
     * @return
     */
    @Override
    public Result signCount() {
        //1、获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //2、获取日期
        LocalDateTime now = LocalDateTime.now();
        //3、拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //4、获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //5、获取本月截止今天为止的连续签到次数   BITFIELD key GET u[dayOfMonth] 0
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key, BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        if (result == null || result.isEmpty()) {
            //无结果
            return Result.ok("没有任何签到结果");
        }
        Long num = result.get(0);
        if (num == null || num == 0) {
            return Result.ok(0);
        }
        //6、循环遍历
        int count = 0;
        while (true) {
            //7、让这个数字和1做与运算，得到数字最后一个bit位,判断bit位是否为0
            if ((num & 1) == 0) {
                //如为0，则表示未签到——结束
                break;
            } else {
                //不为0，说明已签到，计数器+1
                count++;
            }
            //把数字右移一位，抛弃最后一个bit位，继续下一个bit位
            num >>>= 1;
        }
        return Result.ok(count);
    }


    /**
     * 创建用户
     *
     * @param phone
     * @return
     */
    private User CreateUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        user.setIcon(LOGON_USER_ICON);
        //保存用户
        save(user);
        return user;
    }
}




